package daobeauty.interceptor.invoke.parser.operator;

import java.util.List;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import daobeauty.util.Stack;

public class BetweenOperator implements Operator {
	private String propertyName;
	private Class argumentTypeLo;
	private Class argumentTypeHi;
	
	public BetweenOperator(String propertyName, Class argumentTypeLo, Class argumentTypeHi){
		this.propertyName = propertyName;
		this.argumentTypeHi = argumentTypeHi;
		this.argumentTypeLo = argumentTypeLo;
	}
	
	public Criterion createCriterion(Stack argumentStack) {
		Object lo = argumentStack.pop();
		Object hi = argumentStack.pop();
		if (lo!=null && hi!=null){
			return Restrictions.between(propertyName, lo, hi);
		}
		else if (hi==null && lo==null){
			return Restrictions.isNull(propertyName);
		}
		else if (hi==null){
			return Restrictions.ge(propertyName, lo);
		}
		else{
			return Restrictions.le(propertyName, hi);
		}
	}
	
	@SuppressWarnings("unchecked")
	public String toHqlQuery(Stack argumentStack, List usedArguments){
		Object lo = argumentStack.pop();
		Object hi = argumentStack.pop();
		if (lo!=null && hi!=null){
			usedArguments.add(lo);
			usedArguments.add(hi);
			return "d."+propertyName+" BETWEEN(?, ?)";
		}
		else if (hi==null && lo==null){
			return "d."+propertyName+" IS NULL";
		}
		else if (hi==null){
			usedArguments.add(lo);
			return "d."+propertyName+" >= ?";
		}
		else{
			usedArguments.add(hi);
			return "d."+propertyName+" <= ?";
		}
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((argumentTypeHi == null) ? 0 : argumentTypeHi.hashCode());
		result = prime * result
				+ ((argumentTypeLo == null) ? 0 : argumentTypeLo.hashCode());
		result = prime * result
				+ ((propertyName == null) ? 0 : propertyName.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final BetweenOperator other = (BetweenOperator) obj;
		if (argumentTypeHi == null) {
			if (other.argumentTypeHi != null)
				return false;
		} else if (!argumentTypeHi.equals(other.argumentTypeHi))
			return false;
		if (argumentTypeLo == null) {
			if (other.argumentTypeLo != null)
				return false;
		} else if (!argumentTypeLo.equals(other.argumentTypeLo))
			return false;
		if (propertyName == null) {
			if (other.propertyName != null)
				return false;
		} else if (!propertyName.equals(other.propertyName))
			return false;
		return true;
	}

	public int getAmountArguments() {
		return 2;
	}

	public int getTotalAmountArguments() {
		return 2;
	}

	public String toTotalString() {
		return propertyName+" BETWEEN("+argumentTypeLo.getName()+", "+argumentTypeHi.getName()+")";
	}
	
	public String toString(){
		return toTotalString();
	}
}
